package com.example.demo.config.task;

import javax.annotation.Resource;

import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.task.TaskExecutorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import lombok.Data;

/**
 * @author huangke
 * @description 线程池配置
 * @date 2020/12/29
 */
@Configuration
public class CustomerTaskExecutorBuilder {

    @Resource
    private TaskExecutorBuilder builder;

    public TaskExecutorBuilder taskExecutorBuilder(CustomerTaskExecutorProperties properties) {
        CustomerTaskExecutorBuilder.Pool pool = properties.getPool();
        CustomerTaskExecutorBuilder.Shutdown shutdown = properties.getShutdown();
        // 设置核心线程数
        builder = builder.corePoolSize(pool.getCoreSize());
        // 设置最大线程数
        builder = builder.maxPoolSize(pool.getMaxSize());
        //配置队列大小
        builder = builder.queueCapacity(pool.getQueueCapacity());
        // 设置线程活跃时间（秒）
        builder = builder.keepAlive(pool.getKeepAlive());
        // 设置默认线程名称
        builder = builder.threadNamePrefix(properties.getThreadNamePrefix());
        // 等待所有任务结束后再关闭线程池
        builder = builder.awaitTermination(shutdown.isAwaitTermination());
        // 等待时间到期后强行终止所有线程
        builder = builder.awaitTerminationPeriod(shutdown.getAwaitTerminationPeriod());
        builder = builder.allowCoreThreadTimeOut(pool.isAllowCoreThreadTimeout());
        return builder;
    }

    @Bean
    @Primary
    public CustomerTaskExecutorProperties getTaskExecutorProperties() {
        return new CustomerTaskExecutorProperties();
    }

    @Data
    @EnableConfigurationProperties
    public static class CustomerTaskExecutorProperties {
        private CustomerTaskExecutorBuilder.Pool pool = new CustomerTaskExecutorBuilder.Pool();
        private CustomerTaskExecutorBuilder.Shutdown shutdown = new CustomerTaskExecutorBuilder.Shutdown();
        private String threadNamePrefix = "customer-default-";
    }

    public static class Pool extends TaskExecutionProperties.Pool {
    }

    public static class Shutdown extends TaskExecutionProperties.Shutdown {
    }
}